﻿using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
using Orchard.Logging;
using Orchard.Widgets.Models;
using Utils.WidgetInserter.Services;

namespace Utils.WidgetInserter.Models
{
    public class WidgetParser {

        public WidgetParser(ILogger logger)
        {
            Logger = logger;
        }

        public ILogger Logger { get; set; }

        private const string GROUP_NAME = "name";

        public string Replace(string text, IContentManager contentManager, ISettingsService settingsService) {                        
            if (string.IsNullOrEmpty(text))
                return text;
        
            //var stopwatch = new Stopwatch();
            //stopwatch.Start();

            string format = GetFormat(settingsService);            

            var regex = new Regex(format, RegexOptions.IgnoreCase); 

            var strBuilder = new StringBuilder(text);
            
            foreach (Match match in regex.Matches(text)) {
                var name = match.Groups[GROUP_NAME];
                
                if (!string.IsNullOrEmpty(name.Value)) {
                    var widget = contentManager.Query<WidgetPart, WidgetPartRecord>()
                        .Where(x => x.Name == name.Value)
                        .List()
                        .FirstOrDefault();                    

                    if (widget != null) {
                        var w = contentManager.BuildDisplay(widget);
                        var markup = ((ContentItem)w.ContentItem).As<BodyPart>().Text;                        
                        strBuilder.Replace(match.Value, markup);
                    }
                }
            }

            //stopwatch.Stop();
            //Logger.Debug("Widget parser: " + stopwatch.Elapsed.TotalSeconds);
            //Logger.Error("Widget parser: " + stopwatch.Elapsed.TotalSeconds);

            return strBuilder.ToString();
        }

        private string GetFormat(ISettingsService settingsService)
        {
            var settings = settingsService.GetSettings();
            if (settings != null && !string.IsNullOrEmpty(settings.Format))
                return settings.Format;
            
            return SettingsPartRecord.DefaultFormat;
        }
    }
}